/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.data.beetl.ami

import com.gitee.minimalismstyle.fresh.common.data.commons.annotation.Unique
import org.beetl.sql.core.SQLManager
import org.beetl.sql.core.SQLReady
import org.beetl.sql.mapper.MapperInvoke
import org.springframework.security.util.FieldUtils
import java.lang.reflect.Method

/**
 * 唯一属性验证 beetl Ami
 * @author maoxiaodong
 */
class IsUniqueAmi : MapperInvoke() {

    override fun call(sm: SQLManager, entityClass: Class<Any>, m: Method?, args: Array<out Any>): Any {
        val fields = entityClass.declaredFields.filter { it.isAnnotationPresent(Unique::class.java) }
        return if (fields.isNotEmpty()) {//没有唯一属性默认返回true
            true
        } else {

            val entity = args[0]
            val value = fields[0].get(entity)
            val tableName = sm.dbStyle.nameConversion.getTableName(entityClass)
            val uniqueName = sm.dbStyle.nameConversion.getColName(fields[0].name)
            val idCol = sm.getClassDesc(entityClass).idCols.first()
            val idName = sm.getTableDesc(tableName).idNames.first()
            val id = FieldUtils.getProtectedFieldValue(idCol, entity)


            var sql = "select count(1) from `$tableName` where `$uniqueName` = ?"
            val sqlReady = if(id != null){
                sql = "${sql} and `${idName}` = ?"
                SQLReady(sql, value, id)
            }else{
                SQLReady(sql, value)
            }
            val num = sm.execute(sqlReady, Int::class.java)[0]
            0 == num
        }
    }
}